package Hot100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class spiralOrder {
    public static void main(String[] args) {
        int[][] matrix = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15},{16,17,18,19,20},{21,22,23,24,25}};
        System.out.println(spiralOrder(matrix));
    }
    public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> order = new ArrayList<Integer>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return order;
        }
        int rows = matrix.length, columns = matrix[0].length;
        int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
        int circle = 1;
        int count = 0;
        int change = 0;
        while(count < (right + 1) * (bottom + 1)){
            order.add(matrix[top][left]);
            count++;
            change++;
            if(left < right - circle + 1 && top == circle - 1)
                left ++;
            else if (left == right - circle + 1 && top < bottom - circle + 1) {
                top ++;
            } else if (top == bottom - circle + 1 && left > circle - 1) {
                left --;
            } else if (left == circle - 1 && top > circle) {
                top --;
            }
            if(change == (matrix.length + matrix[0].length - 4 * (circle - 1)) * 2 - 4){
                circle ++;
                left ++;
                change = 0;
            }

        }
        return order;

    }

}
